#include "adduserdialog.h"
#include "../../ui/ui_adduserdialog.h"
#include "database.h"
#include <QMessageBox>

AddUserDialog::AddUserDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddUserDialog)
{
    ui->setupUi(this);
}

AddUserDialog::~AddUserDialog() {
    delete ui;
}

void AddUserDialog::on_addButton_clicked() {
    QString username = ui->usernameEdit->text().trimmed();
    QString password = ui->passwordEdit->text().trimmed();
    QString role = ui->roleComboBox->currentText();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "失败", "用户名和密码不能为空");
        return;
    }

    if (Database::userExists(username.toStdString())) {
        QMessageBox::warning(this, "失败", "用户已存在");
        return;
    }

    if (Database::addUserWithRole(username.toStdString(), password.toStdString(), role.toStdString())) {
        QMessageBox::information(this, "成功", "用户添加成功！");
        this->accept();
    } else {
        QMessageBox::warning(this, "失败", "用户添加失败！");
    }
}
